﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace WP7Guide
{
    public partial class EventPage : PhoneApplicationPage
    {
        public EventPage()
        {
            InitializeComponent();
            ((ApplicationBarIconButton) ApplicationBar.Buttons[0]).Text = AppResources.AddTimer;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var bid = NavigationContext.QueryString["bid"];
            var cid = NavigationContext.QueryString["cid"];
            var eid = NavigationContext.QueryString["eid"];
            int bouquetId;
            int channelId;
            int eventId;

            int.TryParse(bid, out bouquetId);
            int.TryParse(cid, out channelId);
            int.TryParse(eid, out eventId);

            service = App.ViewModel.Bouquets[bouquetId].Services[channelId];
            this.DataContext = service.Events[eventId];
        }
        ServiceViewModel service;
        private void AddTimer_Click(object sender, EventArgs e)
        {
            if (App.IsTrial)
            {
                NavigationService.Navigate(new Uri("/BuyPage.xaml", UriKind.Relative));
            }
            else
            {
                var e2event = DataContext as EventViewModel;
                if (e2event != null)
                {
                    WebClient webClient = new WebClient();
                    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                    var request =
                        new Uri("http://" + App.Settings.DreamboxHost + "/web/timeraddbyeventid?sRef=" + service.RefID +
                                "&eventid=" + e2event.EventId);
                    webClient.OpenReadAsync(request);
                }
            }
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else
            {
                App.ViewModel.LoadTimer();
                MessageBox.Show(AppResources.TimerAdded);
            }
        }
    }
}